from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5.QtCore import pyqtProperty
from PyQt5 import QtCore, QtWidgets
import os
from collections import OrderedDict
from lib.pconf import Config, sys_cfg

extensions = ['*.%s ' % fmt.data().decode("ascii").lower() for fmt in QtGui.QImageReader.supportedImageFormats()]

class QIComboBox(QtWidgets.QComboBox):
    def __init__(self,parent=None):
        super(QIComboBox, self).__init__(parent)


class MagicWizard(QtWidgets.QWizard):
    def __init__(self, parent=None, cfg=None):
        super(MagicWizard, self).__init__(parent)
        self.addPage(PageProject(self, cfg))
        self.addPage(PageFileList(self, cfg))
        self.addPage(PageLabelList(self, cfg))
        self.addPage(PageModelList(self, cfg))
        self.setWindowTitle("新建项目")
        self.resize(640,480)

class PageProject(QtWidgets.QWizardPage):
    def __init__(self, parent=None, cfg=None):
        super(PageProject, self).__init__(parent)
        self.cfg = cfg

        #create project name
        self.label1 = QtWidgets.QLabel()
        self.label1.setText("项目名称")

        self.projName = QtWidgets.QLineEdit()
        self.projName.setText("")


        #find project path
        self.label2 = QtWidgets.QLabel()
        self.label2.setText("项目路径")

        self.projPath = QtWidgets.QLineEdit()
        self.projPath.setText("")

        self.pb = QtWidgets.QPushButton()
        self.pb.setObjectName("browse")
        self.pb.setText("选择")

        layout = QtWidgets.QGridLayout()
        layout.addWidget(self.label1, 0, 0)
        layout.addWidget(self.projName, 0, 1, 1, 2)
        layout.addWidget(self.label2, 1, 0)
        layout.addWidget(self.projPath, 1, 1)
        layout.addWidget(self.pb, 1, 2)

        self.setLayout(layout)
        self.pb.clicked.connect(self.button_click)

        self.absolute_path = None

    def button_click(self):
        # absolute_path is a QString object
        absolute_path = QtWidgets.QFileDialog.getExistingDirectory(self,
                  "选取文件夹",
                  "./")
        #print(absolute_path)
        if absolute_path is not "":
            self.absolute_path = absolute_path
        self.projPath.setText(self.absolute_path)

    def validatePage(self):
        if self.projPath.text() != "" and self.projName.text() != "" and os.path.exists(self.projPath.text()):
            self.cfg["project_name"] = self.projName.text()
            self.cfg["project_path"] = self.projPath.text()
            return True
        return False


class PageFileList(QtWidgets.QWizardPage):
    def __init__(self, parent=None, cfg=None):
        super(PageFileList, self).__init__(parent)
        self.cfg = cfg
        self.fileListWidget = QtWidgets.QListWidget()

        new_file = QtWidgets.QPushButton('添加')
        del_file = QtWidgets.QPushButton('删除')
        buttonLayout = QtWidgets.QHBoxLayout()
        buttonLayout.addWidget(new_file)
        buttonLayout.addWidget(del_file)

        buttonContainer = QtWidgets.QWidget()
        buttonContainer.setLayout(buttonLayout)

        labelTile = QtWidgets.QLabel()
        labelTile.setText("文件列表")

        filelistLayout = QtWidgets.QVBoxLayout()
        filelistLayout.setContentsMargins(0, 0, 0, 0)
        filelistLayout.addWidget(labelTile)
        filelistLayout.addWidget(self.fileListWidget)
        filelistLayout.addWidget(buttonContainer)

        self.setLayout(filelistLayout)
        new_file.clicked.connect(self.addNewFile)
        del_file.clicked.connect(self.delExistFile)

        #self.filePath = '/home/a409/users/liqing/project/detection/data'
        self.filePath = [sys_cfg["system_rootpath"]]
        print(self.filePath)
        self.fileList = []

    def addNewFile(self):
        try:
            if self.filePath == [] or self.filePath=='':
                self.filePath = QtWidgets.QFileDialog.getOpenFileNames(self,
                                                       "选取文件夹",
                                                       sys_cfg["system_rootpath"],
                                                       "".join(extensions) )[0]
            else:
                self.filePath = QtWidgets.QFileDialog.getOpenFileNames(self,
                                                      "选取文件夹",
                                                      os.path.dirname(self.filePath[0]),
                                                      "".join(extensions) )[0]
            print(self.filePath)
            for Path in self.filePath:
                if Path not in self.fileList:
                    self.fileListWidget.addItem(Path)
                    self.fileList.append(Path)
            #print(self.fileList)

        except:
            pass

    def delExistFile(self):
        item = self.fileListWidget.currentItem()
        pop_name = item.text()
        row = self.fileListWidget.row(item)
        self.fileListWidget.takeItem(row)
        self.fileList.remove(pop_name)

    def validatePage(self):
        if len(self.fileList) > 0:
            self.cfg['image_list'] = self.fileList
            return True
        return False




class PageLabelList(QtWidgets.QWizardPage):
    def __init__(self, parent=None, cfg=None):
        super(PageLabelList, self).__init__(parent)
        self.cfg = cfg
        self.fileLabelWidget = QtWidgets.QListWidget()

        new_label = QtWidgets.QPushButton('添加')
        del_label = QtWidgets.QPushButton('删除')
        buttonLayout = QtWidgets.QHBoxLayout()
        buttonLayout.addWidget(new_label)
        buttonLayout.addWidget(del_label)

        buttonContainer = QtWidgets.QWidget()
        buttonContainer.setLayout(buttonLayout)

        labelTile = QtWidgets.QLabel()
        labelTile.setText("标签列表")

        filelabelLayout = QtWidgets.QVBoxLayout()
        filelabelLayout.setContentsMargins(0, 0, 0, 0)
        filelabelLayout.addWidget(labelTile)
        filelabelLayout.addWidget(self.fileLabelWidget)
        filelabelLayout.addWidget(buttonContainer)

        self.setLayout(filelabelLayout)
        new_label.clicked.connect(self.addNewLabel)
        del_label.clicked.connect(self.delExistLabel)

        self.labelList = []
        self.initList()

    def initList(self):
        labs = self.cfg["labels"]
        labs_ord = OrderedDict(sorted(labs.items(), key=lambda t: t[0]))
        for (lk, lv) in labs_ord.items():
            self.addNewLabel()
            self.newlabel.setText(lv)

    def addNewLabel(self):
        # create label name
        self.newlabel = QtWidgets.QLineEdit()
        item = QtWidgets.QListWidgetItem()

        self.fileLabelWidget.addItem(item)
        self.fileLabelWidget.setItemWidget(item, self.newlabel)

    def delExistLabel(self):
        item = self.fileLabelWidget.currentItem()
        row = self.fileLabelWidget.row(item)
        self.fileLabelWidget.takeItem(row)

    def validatePage(self):
        count = self.fileLabelWidget.count()
        for i in range(count):
            name = self.fileLabelWidget.itemWidget(self.fileLabelWidget.item(i)).text()
            self.labelList.append(name)
        if len(self.labelList) > 0:
            self.cfg['labels'] = {}
            for idx, i in enumerate(self.labelList):
                self.cfg['labels'][idx] = i
            return True
        return False


class PageModelList(QtWidgets.QWizardPage):
    def __init__(self, parent=None, cfg=None):
        super(PageModelList, self).__init__(parent)
        self.cfg = cfg
        self.label = QtWidgets.QLabel()
        self.label.setText("模型类型")
        self.comboBox = QIComboBox(self)
        self.comboBox.addItem("SCSANet")
        layout = QtWidgets.QHBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(self.comboBox)
        self.setLayout(layout)

    def validatePage(self):
        model_name = self.comboBox.currentText()
        return True
